package net.sparrow.cmd;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.sparrow.Sparrow;
import net.sparrow.module.Module;

/**
 *
 *
 */
public class CommandHandler {
	ArrayList<SpCommand> cmds = new ArrayList();
	
	/**
	 * After it has been determined that the dataID in question belongs to
	 * this module's commandhandler, it sends it here
	 * @param args
	 * @return if the command was handled or not
	 */
	public boolean handleCommand(String[] args) {
		for(SpCommand cmd : cmds) {
			if(cmd.keyword.equals(args[1]) && args[0].equals(cmd.dataId)) {
				cmd.execute(args);
				return true;
			}
		}
		return false;
	}

	public CommandHandler withDefaultToggle(String dataId) {
		cmds.add(new DefaultSetCmdHandler(dataId));
		cmds.add(new DefaultToggleCmdHandler(dataId));
		return this;
	}
	
	public CommandHandler withDefaultSet(String idataId) {
		cmds.add(new DefaultSetCmdHandler(idataId));
		return this;
	}
	
	public CommandHandler withDefaultAddRem(String idataId) {
		cmds.add(new DefaultAddCmdHandler(idataId));
		cmds.add(new DefaultRemCmdHandler(idataId));
		return this;
	}

	private class DefaultSetCmdHandler extends SpCommand {
		
		public DefaultSetCmdHandler(String idataId) {
			super("set",idataId);
		}
		
		public void execute(String[] args) {
			if(args.length == 0) {
				Sparrow.cmds().addErrMsg("<dataID> set <value>");
			}
			if(!Sparrow.cmds().setData(dataId, args[2])) {
				Sparrow.cmds().addErrMsg("Failed to set data. Wrong data type/ID?");
			}
		}
	}
	
	private class DefaultToggleCmdHandler extends SpCommand {
		
		public DefaultToggleCmdHandler(String dataId) {
			super("toggle", dataId);
		}
		
		public void execute(String[] args) {
			Sparrow.data().setData(dataId, !(Boolean)Sparrow.data().getData(dataId));
		}
	}
	
	private class DefaultAddCmdHandler extends SpCommand {
		
		public DefaultAddCmdHandler(String dataId) {
			super("add", dataId);
		}
		
		public void execute(String[] args) {
			if(args.length == 0) {
				Sparrow.cmds().addErrMsg("<dataID> add <value>");
			}
			if(!Sparrow.cmds().addToData(dataId, args[2])) {
				Sparrow.cmds().addErrMsg("Incorrect Data Type.");
			}
		}
	}
	
	private class DefaultRemCmdHandler extends SpCommand {
		
		public DefaultRemCmdHandler(String dataId) {
			super("rem",dataId);
		}
		
		public void execute(String[] args) {
			if(args.length == 0) {
				Sparrow.cmds().addErrMsg("<dataID> rem <value>");
			}
			if(!Sparrow.cmds().remFromData(dataId, args[2])) {
				Sparrow.cmds().addErrMsg("Incorrect Data Type.");
			}
		}
	}
	
}


